package com.legend.security;

import com.legend.utils.ReturnResult;
import com.legend.utils.Status;
import com.legend.utils.StringUtils;
import com.legend.utils.i18nUtils;
import com.wh.beans.LoginInfoCookie;
import com.wh.service.IExt.ISysUserBaseService;
import com.wh.service.impl.CommonBo;
import com.wh.service.impl.SysUserBaseService;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

public class AuthorityInterceptor extends HandlerInterceptorAdapter {
    Logger logger = Logger.getLogger(AuthorityInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String methodName = ((HandlerMethod) handler).getMethod().getName();
        logger.info("当前访问的方法名:" + methodName);
        ReturnResult result = new ReturnResult();
        // Annotation[][] a=currentMethod.getParameterAnnotations();
        // String returnType = currentMethod.getReturnType().getSimpleName();

        // ModelAndView, Model, ModelMap, Map,View, String, void
        // logger.info("方法返回类型" + returnType);
        /*
		 * logger.info("开始");
		 * 
		 * if (currentMethod.isAnnotationPresent(LogInfo.class)) {
		 * logger.info("进来了"); LogInfo logInfo =
		 * currentMethod.getAnnotation(LogInfo.class); Class clazz =
		 * logInfo.ModelClass(); Field field[] = clazz.getDeclaredFields();
		 * StringBuffer sb = new StringBuffer(); logger.info("长度 :" +
		 * field.length); for (Field fd : field) {
		 * System.out.println(fd.getName());
		 * 
		 * } return true;
		 * 
		 * }
		 */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Method currentMethod = ((HandlerMethod) handler).getMethod();
        String serverName = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
        if (currentMethod.isAnnotationPresent(Authority.class)) {// 只对需要验证的进行验证
            LoginInfoCookie loginCookie = CommonBo.getInstance().checkLogin(request);

            Authority authority = currentMethod.getAnnotation(Authority.class);
            if (loginCookie == null) {// 判断是否登录
                // if (returnType.equals("String")) {//
                // 应该再加一步判断有@responsebody注解的方法
                if (currentMethod.isAnnotationPresent(ResponseBody.class)) {
                    result.setMsg(i18nUtils.getVal("200001005"));
                    result.setStatus(Status.NOLOGIN);
                    StringUtils.write(response, result.toString());
                } else
                    response.sendRedirect(serverName + "login.do");
                return false;
            } else {
                Integer isSuper = loginCookie.getIsSuper();
                if (isSuper != null && isSuper.equals(1)) {
                    return true;
                } else if (authority.permissionType().length > 0 && authority.permissionType()[0] != PermissionType.None) {
                    ISysUserBaseService bo = SysUserBaseService.getInstance();
                    result = bo.checkPower(authority.permissionType(), authority.moduleCode(), request);
                    if (result.getStatus() == Status.SUCCESS) {
                        logger.debug("验证通过");
                        return true;
                    } else {
                        if (currentMethod.isAnnotationPresent(ResponseBody.class)) {
                            StringUtils.write(response, result.toString());
                        } else
                            response.sendRedirect(serverName + "nopower.do");
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("完成后--------afterCompletion");
    }


}